class Creditcard < ActiveRecord::Base
  belongs_to :account
  belongs_to :terminal_group
  attr_accessible :account_id, :terminal_group_id, :duration_total, :duration_used, :duration_rest, :traffic_total, :traffic_used, :traffic_rest, :limit_up, :limit_down, :rest_times

  def avaliable?
    (duration_rest > 0 || duration_rest == -1) && (traffic_rest > 0  || traffic_rest == -1)
  end

  def refresh!
    if !rest_times || (!avaliable? && rest_times > 0)
      strategy = choose_traffic_strategy
      self.rest_times = strategy.times if !self.rest_times
      strategy.duration_total *= account.level unless strategy.duration_total == -1
      strategy.traffic_total *= account.level unless strategy.traffic_total == -1
      self.duration_total = self.duration_rest = strategy.duration_total
      self.traffic_total = self.traffic_rest = strategy.traffic_total
      self.duration_used = self.traffic_used = 0
      self.limit_up = strategy.limit_up
      self.limit_down = strategy.limit_down
      self.rest_times -= 1
      save!
    end
  end

  private
    def choose_traffic_strategy
      # rule 1 : completely match
      strategy = TrafficStrategy.is_on.where(terminal_group_id: terminal_group_id, account_group_id: account.account_group_id).first
      # rule 2 : terminal group match
      strategy = TrafficStrategy.is_on.where(terminal_group_id: terminal_group_id, account_group_id: nil).first if strategy == nil
      # rule 3 : account group match
      strategy = TrafficStrategy.is_on.where(terminal_group_id: nil, account_group_id: account.account_group_id).first if strategy == nil
      # rule 4 : terminal & account nil
      strategy = TrafficStrategy.is_on.where(terminal_group_id: nil, account_group_id: nil).first if strategy == nil
      # rule 5 : no limit
      strategy = TrafficStrategy.new(duration_total: -1, limit_down: -1, limit_up: -1, traffic_total: -1, times: 1) if strategy == nil
      strategy  
    end

end
